<?php

/**
 * ringtone actions.
 *
 * @package    sf_sandbox
 * @subpackage ringtone
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 2288 2006-10-02 15:22:13Z fabien $
 */
class ringtoneActions extends autoringtoneActions
{	
	public function executeList()
  	{
   		//$this->processSort();
             
    	$this->processFilters();

    	$this->filters = $this->getUser()->getAttributeHolder()->getAll('sf_admin/ringtone/filters');        
        //========================================

        if (isset($this->filters['creator_name'])||(isset($this->filters['creator_name']))||(isset($this->filters['creator_id']))){
            if (isset($this->filters['creator_name'])) {
                    $username = trim($this->filters['creator_name']);
            }else{
                    $username = null;
            }

            if (isset($this->filters['creator_phone'])) {
                $userphone = trim($this->filters['creator_phone']);
            }else{
                $userphone = null;
            }
            if (isset($this->filters['creator_id'])) {
                $userId = trim($this->filters['creator_id']);
            }else{
                $userId = null;
            }
            if ((strlen($username) > 0)||(strlen($userphone) > 0)||(strlen($userId) > 0)){

                $c = new Criteria();

                if(strlen($userId) > 0){
                    $c->add(UserPeer::ID, $userId);
                }else if (strlen($userphone) > 0) {
                    $userphone = iringback::checkPhoneNumber($userphone)->phone;
                    $c->add(UserPeer::PHONE, $userphone);
                }else if (strlen($username) > 0) {
                    $c->add(UserPeer::USERNAME, $username);
                }

                $user = UserPeer::doSelectOne($c);

                if ($user != null)
                {
                    $this->filters['creator_id'] = $user->getId();
                    $this->filters['creator_name'] = $user->getUsername();
                    $this->filters['creator_phone'] = $user->getPhone();
                }
            }
        }

        //========================================
        
    	// pager
    	$this->pager = new sfPropelPager('Ringtone', 20);
    	$c = new Criteria();
    	
    	$this->nhac = null;
    	
    	if ($this->hasRequestParameter('nhac'))
    	{
    		sfContext::getInstance()->getLogger()->info('has nhac in list');
    		
    	    $this->nhac = $this->getRequestParameter('nhac');
    	      $this->duyet = $this->getRequestParameter('duyet');
               
    	    #var_dump($this->nhac);exit();
    	    
    	    $this->uri = 'ringtone/list?nhac=' . $this->getRequestParameter('nhac') . '&'; 
    	    
    		$c->addJoin(RingtonePeer::ID, RingtoneStatusPeer::RINGTONE_ID);
    		
    		if ($this->getRequestParameter('nhac') == 'chuong')
    		{
    		    if ($this->hasRequestParameter('duyet'))
    		    {
                        $this->duyet = $this->getRequestParameter('duyet');
    		        $this->uri .= 'duyet=' . $this->getRequestParameter('duyet') . '&';
                        if ($this->getRequestParameter('duyet') == 'roi')
                        {
                            $c->add(RingtoneStatusPeer::RT_APPROVE, 1);
                            $c->addDescendingOrderByColumn(RingtonePeer::LAST_UPDATE_DATETIME);
                        }
                        elseif ($this->getRequestParameter('duyet') == 'tuchoi')
                        {
                            $c->add(RingtoneStatusPeer::RT_APPROVE, 2);
                            $c->addDescendingOrderByColumn(RingtonePeer::LAST_UPDATE_DATETIME);
                        }
                        elseif ($this->getRequestParameter('duyet') == 'vegachuaduyet')
                        {
                            $c->add(RingtoneStatusPeer::RT_APPROVE, 0);
                        }
    		    		elseif ($this->getRequestParameter('duyet') == 'vmschuaduyet')
                        {
                            $c->add(RingtoneStatusPeer::RT_APPROVE, 3);
                            $c->addDescendingOrderByColumn(RingtoneStatusPeer::RT_APPROVE_DATETIME);
                        }
                        elseif($this->getRequestParameter('duyet') == 'tatca')
                        {
                        	$c->add(RingtoneStatusPeer::RT_APPROVE, array(0,1,2,3), Criteria::IN);
                        }
                    }
                }
                elseif ($this->getRequestParameter('nhac') == 'cho')
                {
                    if ($this->hasRequestParameter('duyet') )
                    {
                        $this->duyet = $this->getRequestParameter('duyet');
                        $this->uri .= 'duyet=' . $this->getRequestParameter('duyet') . '&';
		        
                    if ($this->getRequestParameter('duyet') == 'chuaupload')
                    {
                        $c->add(RingtoneStatusPeer::RT_APPROVE, array(1,3), Criteria::IN); //Danhpt add 20110701
                        $c->add(RingtoneStatusPeer::RBT_APPROVE, NULL);
                        //$c->add(RingtoneStatusPeer::RBT_APPROVE,array(0,1,2),Criteria::NOT_IN);
                        //$c->add(RingtoneStatusPeer::RT_DELETE, 2, Criteria::NOT_EQUAL);
                    }
                    elseif ($this->getRequestParameter('duyet') == 'choduyet')
                    {
                    	//$c->add(RingtoneStatusPeer::RT_APPROVE, array(1,3), Criteria::IN); //Danhpt add 20110708
                        $c->add(RingtoneStatusPeer::RBT_APPROVE, 0);
                    }
                    elseif ($this->getRequestParameter('duyet') == 'roi')
                    {
                        $c->add(RingtoneStatusPeer::RBT_APPROVE, 1);
                    }
                    elseif ($this->getRequestParameter('duyet') == 'tuchoi')
                    {
                        $c->add(RingtoneStatusPeer::RBT_APPROVE, 2);
                    }
                    elseif ($this->getRequestParameter('duyet') == 'tatca')
                    {
                    	//All ringbacktone
                    	//$c->add(RingtoneStatusPeer::RT_APPROVE, array(1,3), Criteria::IN); //Danhpt add 20110708
                    }
                    
                }
            }
            $c->addDescendingOrderByColumn(RingtonePeer::CREATED_DATETIME);
            }
            else
            {
                $this->uri = 'ringtone/list?';
        }
		    	
    	$this->addSortCriteria($c);
    	$this->addFiltersCriteria($c);
    	$this->pager->setCriteria($c);
    	$this->pager->setPage($this->getRequestParameter('page', $this->getUser()->getAttribute('page', 1, 			'sf_admin/ringtone')));
    	$this->pager->init();
    	
    	// save page
    	if ($this->getRequestParameter('page')) {
        	$this->getUser()->setAttribute('page', $this->getRequestParameter('page'), 'sf_admin/ringtone');
    	}
    	
  	}
	
	
	//////////////////////////////////////
	/////////  RINGTONE EDIT  //////////////
	/////////////////////////////////////
	
 public function executeEdit()
  {
    $this->ringtone = $this->getRingtoneOrCreate();

    if ($this->getRequest()->getMethod() == sfRequest::POST)
    {
      $this->updateRingtoneFromRequest();

      $this->saveRingtone($this->ringtone);
      $this->ringtone->updatecatename();
      
      if (!$this->getRequestParameter('save_and_add') && !$this->getRequestParameter('save_and_list')) {      
      	$ringtone = $this->getRequestParameter('ringtone');
      	if (isset($ringtone['username_sannhac'])) {
      		$this->updateUsernameSannhac($this->ringtone->getId(), $ringtone['username_sannhac']);
      		$this->updateIsUpload($this->ringtone->getId(), $ringtone['is_upload']);
      	}        
      }

      $this->setFlash('notice', 'Thông tin đã được cập nhật');

      if ($this->getRequestParameter('save_and_add'))
      {
        return $this->redirect('ringtone/create');
      }
      else if ($this->getRequestParameter('save_and_list'))
      {
        return $this->redirect('ringtone/list');
      }
      else
      {
        return $this->redirect('ringtone/edit?id='.$this->ringtone->getId());
      }
    }
    else
    {
    	$ringid = $this->ringtone->getId();
      	$userId = $this->ringtone->getCreatorId();
       	$name = $this->ringtone->getName();
    	
      	$this->labels = $this->getLabels();
      	$this->Getringtone_Related($userId,$name,$ringid);
    }
  }
  
	//////////////////////////////////////
	/////////  RINGTONE STATUS  //////////////
	/////////////////////////////////////
	
	public function executeRtModerate()
    {
    	$this->reallyModerate('rt');

    	// Thangtv2 
    	//add Lý do từ chối 
    	$this->list_reasons =  RtApproveCommentPeer::doSelect(new Criteria());
    	
    	// Show trang thai dong bo
    	$ringtone = $this->getRingtoneOrCreate();
    	$ring_sys = $ringtone ->getRingtoneSynchronize();
    	
    	
    	$rt =  new Criteria();
		$rt->add(RingtoneSynchronizePeer::RING_ID, $ringtone->getId());
		$this->ringtone_sys = RingtoneSynchronizePeer::doSelectOne($rt);
    	
    }
    
    public function executeSaveRtModerate()
    {
        $this->setLayout('popup');
        $this->ringtone = $this->getRingtoneOrCreate();
        
        if ($this->getRequest()->getMethod() == sfRequest::POST)
        {
        	$this->updateRingtoneFromRequest();
			$this->updateRtApproveInfo($this->ringtone);
			
			//add by danhpt 2011-10-18 : save valid_datetime,contract_index,contract_index_number to ringtone_extra table
			$rtextra = RingtoneExtraPeer::retrieveByPK($this->ringtone->getId());
			$valid_datetime = $this->getRequestParameter('valid_datetime');
			$contract_index = $this->getRequestParameter('contract_index',0);
			$contract_index_num = $this->getRequestParameter('contract_index_number',0);
			
		  	$rtextra->setValidDatetime($valid_datetime);
		  	$rtextra->setContractIndex($contract_index);
		  	$rtextra->setContractIndexNumber($contract_index_num);
		  	$rtextra->save();
			//end add by danhpt
			
      		$this->saveRingtone($this->ringtone);
      		$this->ringtone->updatecatename();
      		$this->ok = true;
      		
      		// Thangtv2 add for save table synchronize
      		$sys = $this->getRequestParameter('syschornize');
      		
      		$ring_sys = $this->ringtone->getRingtoneSynchronize();
	      	$ring_sys->setRingId($this->ringtone->getId());
      		if($sys){
      			$ringtone = $this->getRequestParameter('ringtone');
      			$ring_sys->setRingName($ringtone['name']);
	      		#$ring_sys->setRingName($this->ringtone->getName());
	      		$ring_sys->setRingLink($this->ringtone->getFullFilePathMp3());
	      		$ring_sys->save();	
      		}else{
      			$ring_sys->delete();	
      		}
		
			// end Thangtv2 add
            
            if (isset($_POST['save_and_redirect']))
            {
                $this->redirect('ringtone/rbtModerate?id=' . $this->getRequestParameter('id') . '&refresh=1');
            }
        }
        
        return;
    }
  
   
  protected function updateRtApproveInfo($ringtone)
  {
  	$ringInfo = $this->getRequestParameter('ringtone');
       
  	$rtstatus = $ringtone->getOrInitRingtoneStatus();
  	
  	$rtstatus->setRtApprove(intval($ringInfo['approved']));
  	
  	//add by danhpt 2011-10-18 : save valid_datetime,contract_index,contract_index_number to ringtone_extra table

  	
  	//end add by danhpt
  	
  	if ($ringInfo['approved'] != 0)
  	{   
  		if ($ringInfo['approved'] == 1)
  		{
  			$ringtone->setRtStatus(1);
		}
  		elseif ($ringInfo['approved'] == 2)
  		{
  			$ringtone->setRtStatus(0);
  			$rtstatus->setRtApproveDescription($ringInfo['approve_description']);
		}
		elseif ($ringInfo['approved'] == 3)
		{
			$ringtone->setRtStatus(0);
		}
		$rtstatus->setRtApproveAdmin($this->getUser()->getUserName());
		$rtstatus->setRtApproveDatetime(date( 'Y-m-d H:i:s', time()));
  	}
  	else
  	{
  		$ringtone->setRtStatus(0);
	}
	
	// delte
	$rtstatus->setRtDelete(intval($ringInfo['delete']));
	if ($ringInfo['delete'] != 0)
  	{
  		// if the ringtone is deleted, the rt_status will be set to 0 
  		// no matter what the approve status
  		$ringtone->setRtStatus(0);
  		
  		if ($ringInfo['delete'] == 2)
  		{
  			$rtstatus->setRtDeleteDescription($ringInfo['delete_description']);
		}
		$rtstatus->setRtDeleteAdmin($this->getUser()->getUserName());
		$rtstatus->setRtDeleteDatetime(date( 'Y-m-d H:i:s', time()));
		
		// Thangtv2 add
		// Neu xoa nhac chuong thi sẽ set trang thai duyet la tu choi
		$ringInfo['approved'] = 2;
		$rtstatus->setRtApprove(2);
		$rtstatus->setRtApproveDescription($ringInfo['approve_description']);
  	}
  	
  }
  /////////////////////////////////////
  /////////  RINGBACKTONE STATUS  //////////////
  /////////////////////////////////////
  
  
	
	public function executeRbtModerate()
    {
        $this->reallyModerate('rbt');
        
        if ($this->hasRequestParameter('refresh') && $this->getRequestParameter('refresh') == 1)
        {
            $this->refresh = true;
        }
        else
        {
            $this->refresh = false;
        }
        
        // thangtv2
        //add Lý do từ chối 
    	$this->list_reasons =  RtApproveCommentPeer::doSelect(new Criteria());
    	
    	// Show trang thai dong bo
    	$ringtone = $this->getRingtoneOrCreate();
    	$ring_sys = $ringtone ->getRingtoneSynchronize();
    	
    	
    	$rt =  new Criteria();
		$rt->add(RingtoneSynchronizePeer::RING_ID, $ringtone->getId());
		$this->ringtone_sys = RingtoneSynchronizePeer::doSelectOne($rt);
    }

    public function executeSaveRbtModerate()
    {        
        $this->setLayout('popup');
        $this->ringtone = $this->getRingtoneOrCreate();
        
        if ($this->getRequest()->getMethod() == sfRequest::POST)
        {                
        	$this->updateRingtoneFromRequest();                 
		$this->updateRbtApproveInfo($this->ringtone);                
      		$this->saveRingtone($this->ringtone);
      		$this->ringtone->updatecatename();
            
            $this->ok = true;
            
            // Thangtv2 add for save table synchronize
      		$sys = $this->getRequestParameter('syschornize');
      		
      		$ring_sys = $this->ringtone->getRingtoneSynchronize();
	      	$ring_sys->setRingId($this->ringtone->getId());
      		if($sys){
	      		$ring_sys->setRingName($this->ringtone->getName());
	      		#$ring_sys->setSysDate();
	      		$ring_sys->setRingLink($this->ringtone->getFullFilePathMp3());
	      		$ring_sys->save();	
      		}else{
      			$ring_sys->delete();	
      		}
		
			// end Thangtv2 add
			
        }
        return;
    }
  	
  	protected function updateRbtApproveInfo($ringtone)
    {
		$ringInfo = $this->getRequestParameter('ringtone');
		$rtstatus = $ringtone->getOrInitRingtoneStatus();
                $denyALl = $this->getRequestParameter('deny_all');
		if ($denyALl == '1'){
                    $ringInfo['approved'] = 2;
                    $ringInfo['crbtStatus'] = 1;
                    $ringInfo['rtStatus'] = 1;
                    $ringInfo['approve_description'] = "Nhạc chờ bị từ chối vì có chất lượng kém!";                    
                }  
		if (($ringInfo['approved'] == '')||($ringInfo['approved'] == null))
		{
			$rtstatus->setRbtApprove(null);
		} else {
                    $rtstatus->setRbtApprove(intval($ringInfo['approved']));
		}
	    //sfContext::getInstance()->getLogger()->err('approved='.$ringInfo['approved']);
	  	
	  	if (($ringInfo['approved'] != 0)&&($ringInfo['approved'] != null))
	  	{	
	  		if ($ringInfo['approved'] == 1)
	  		{
	  			$ringtone->setRbtStatus(1);
			}
	  		elseif ($ringInfo['approved'] == 2)
	  		{      
                                if(isset($ringInfo['crbtStatus'])){
                                    if (isset($ringInfo['rbt_id'])){ $this->hideCRBT($ringInfo['rbt_id']);} //Ẩn bản thu trên CRBT
                                }
                                
                                if(isset($ringInfo['rtStatus'])) {
                                    $ringtone->setRtStatus(0);//Set nhạc chuông tương ứng ở trạng thái từ chối
                                    $rtstatus->setRtApprove(2);
                                    $rtstatus->setRtApproveAdmin($this->getUser()->getUserName());
                                    $rtstatus->setRtApproveDatetime(date('Y-m-d H:i:s', time()));
                                    $rtstatus->setRtApproveDescription($ringInfo['approve_description']);
                                }

	  			$ringtone->setRbtStatus(0);	  			
	  			$rtstatus->setRbtApproveDescription($ringInfo['approve_description']);	  			
			}
			$rtstatus->setRbtApproveAdmin($this->getUser()->getUserName());
			$rtstatus->setRbtApproveDatetime(date('Y-m-d H:i:s', time()));
	  	}
	  	else
	  	{
	  		$ringtone->setRbtStatus(0);
		}
		
		// delte
		$rtstatus->setRbtDelete(intval($ringInfo['delete']));
		if ($ringInfo['delete'] != 0)
	  	{
	  		// if the ringtone is deleted, the rt_status will be set to 0 
	  		// no matter what the approve status
	  		$ringtone->setRbtStatus(0);
	  		
	  		if ($ringInfo['delete'] == 2)
	  		{
	  			$rtstatus->setRbtDeleteDescription($ringInfo['delete_description']);
			}
			$rtstatus->setRbtDeleteAdmin($this->getUser()->getUserName());
			$rtstatus->setRbtDeleteDatetime(date( 'Y-m-d H:i:s', time()));
			
			// Thangtv2 add
			// Neu xoa nhac chuong thi sẽ set trang thai duyet la tu choi
			$ringInfo['approved'] = 2;
			$rtstatus->setRtApprove(2);
			$rtstatus->setRtApproveDescription($ringInfo['approve_description']);
	  	}                 
    }
  
  
  /////////////////////////////    ////////////
  //////////////////////                   //////////
  //////////////////// I DON'T CARE ////////////////////
  //////////////////////////
  //////////////////
  
  
  protected function reallyModerate($type = 'rt')
  {
  		$this->setLayout('popup');
        $id = $this->getRequest()->getParameter('id');

        $ring = RingtonePeer::retrieveByPK($id);
        
        $this->forward404Unless($ring);
        $this->ringtone = $ring;
		
        //add by danhpt 2011-10-18 : get valid_datetime, contract_index, contract_index_number
        $this->ringtone_extra = RingtoneExtraPeer::retrieveByPK($id);
        //end add
        
        $cateList = RingtoneCategoryPeer::getListCategory(new Criteria());

        $this->category_list = array();
        foreach ($cateList as $cate)
        {
            $this->category_list[$cate->getId()] = $cate;
        }
		
	    $this->rtstatus = $ring->getOrInitRingtoneStatus();
	    
	    // Thangtv2 add
	    $this->ringid = $id;
	    
	    // Add bài liên quan
    	$this->ringtone = $this->getRingtoneOrCreate();
    	
    	$ringid = $this->ringtone->getId();
    	$userId = $this->ringtone->getCreatorId();
       	$name = $this->ringtone->getName();
       	
       	$cr = new Criteria();
    	$cr->add(VocalPeer::USER_ID, $userId);
    	$cr->addAscendingOrderByColumn(VocalPeer::CREATED_DATETIME);
    	$this->firstVocal = VocalPeer::doSelectOne($cr);
    	
       	$this->Getringtone_Related($userId,$name,$ringid);
  }
  
  protected function updateRingtoneFromRequest()
  {
    $ringtone = $this->getRequestParameter('ringtone');       

    $ringtoneExtra = $this->ringtone->getRingtoneExtra();
	
	if (!isset($ringtone['composed_by_user']))
	{
		$ringtone['composed_by_user'] = 0;
	}
	
    if (isset($ringtone['name']))
    {
      $this->ringtone->setName(trim($ringtone['name']));
    }

    if (isset($ringtone['rbt_id']))
    {
        if ($ringtone['rbt_id'] == ''){
            $ringtoneExtra->setRbtCode(null);
            $ringtoneExtra->setRbtId(null);
        } else {
            $ringtoneExtra->setRbtCode(trim($ringtone['rbt_id']));
            $ringtoneExtra->setRbtId(trim($ringtone['rbt_id']));
        }
    }
		
    if (isset($ringtone['description']))
    {
      $ringtoneExtra->setDescription(trim($ringtone['description']));
    }
    
    if (isset($ringtone['avatar_path']))
    {
      $this->ringtone->setAvatarPath($ringtone['avatar_path']);
    }
    if (isset($ringtone['file_path_mp3']))
    {
      $this->ringtone->setFilePathMp3($ringtone['file_path_mp3']);
    }
    if (isset($ringtone['file_path_wav']))
    {
      $this->ringtone->setFilePathWav($ringtone['file_path_wav']);
    }
    if (isset($ringtone['duration']))
    {
      $this->ringtone->setDuration($ringtone['duration']);
    }
    if (isset($ringtone['category_id']))
    {
      $this->ringtone->setCategoryId($ringtone['category_id'] ? $ringtone['category_id'] : null);
    }
    if (isset($ringtone['creator_id']))
    {
      $this->ringtone->setCreatorId($ringtone['creator_id'] ? $ringtone['creator_id'] : null);
    }
    if (isset($ringtone['creator_name']))
    {
      $this->ringtone->setCreatorName(trim($ringtone['creator_name']));
    }
    if (isset($ringtone['created_datetime']))
    {
      if ($ringtone['created_datetime'])
      {
        try
        {
          $dateFormat = new sfDateFormat($this->getUser()->getCulture());
          if (!is_array($ringtone['created_datetime']))
          {
            $value = $dateFormat->format($ringtone['created_datetime'], 'I', $dateFormat->getInputPattern('g'));
          }
          else
          {
            $value_array = $ringtone['created_datetime'];
            $value = $value_array['year'].'-'.$value_array['month'].'-'.$value_array['day'].(isset($value_array['hour']) ? ' '.$value_array['hour'].':'.$value_array['minute'].(isset($value_array['second']) ? ':'.$value_array['second'] : '') : '');
          }
          $this->ringtone->setCreatedDatetime($value);
        }
        catch (sfException $e)
        {
          // not a date
        }
      }
      else
      {
        $this->ringtone->setCreatedDatetime(null);
      }
    }
    if (isset($ringtone['rt_status']))
    {
      $this->ringtone->setRtStatus($ringtone['rt_status']);
    }
    if (isset($ringtone['rbt_status']))
    {
      $this->ringtone->setRbtStatus($ringtone['rbt_status']);
    }
    if (isset($ringtone['composer_id']))
    {
      $this->ringtone->setComposerId($ringtone['composer_id']);
    }
    if (isset($ringtone['composer_name']))
    {
      $this->ringtone->setComposerName($ringtone['composer_name']);
    }
    if (isset($ringtone['composed_by_user']))
    {
      $this->ringtone->setComposedByUser($ringtone['composed_by_user']);
    }
    if (isset($ringtone['checknum']))
    {
      $this->ringtone->setChecknum($ringtone['checknum']);
    }
    if (isset($ringtone['total_set']))
    {
      $this->ringtone->setTotalSet($ringtone['total_set']);
    }
    if (isset($ringtone['total_download']))
    {
      $this->ringtone->setTotalDownload($ringtone['total_download']);
    }
    if (isset($ringtone['bonus_set']))
    {
      $this->ringtone->setBonusSet($ringtone['bonus_set']);
    }
    if (isset($ringtone['bonus_download']))
    {
      $this->ringtone->setBonusDownload($ringtone['bonus_download']);
    }    
    if (isset($ringtone['update_type']))
    {
      $this->ringtone->setUpdateType($ringtone['update_type']);
    }   

    if (isset($ringtone['settop_id']))
    {
        //RingtonePeer::testTop();
        
        if ($ringtone['settop_id'] == '1') {
            RingtonePeer::updateTopHot($this->ringtone->getId());
        } else if ($ringtone['settop_id'] == '2') {
            RingtonePeer::removeTopHot($this->ringtone->getId());
        }
    }
    
    if (isset($ringtone['last_update_datetime']))
    {
      if ($ringtone['last_update_datetime'])
      {
        try
        {
          $dateFormat = new sfDateFormat($this->getUser()->getCulture());
                              if (!is_array($ringtone['last_update_datetime']))
          {
            $value = $dateFormat->format($ringtone['last_update_datetime'], 'I', $dateFormat->getInputPattern('g'));
          }
          else
          {
            $value_array = $ringtone['last_update_datetime'];
            $value = $value_array['year'].'-'.$value_array['month'].'-'.$value_array['day'].(isset($value_array['hour']) ? ' '.$value_array['hour'].':'.$value_array['minute'].(isset($value_array['second']) ? ':'.$value_array['second'] : '') : '');
          }
          $this->ringtone->setLastUpdateDatetime($value);
        }
        catch (sfException $e)
        {
          // not a date
        }
      }
      else
      {
        $this->ringtone->setLastUpdateDatetime(null);
      }
    }
  }
  public function hideCRBT($rbtCode){
        $toneProvide_namespace = sfConfig::get('ToneProvide_namespace');
        $toneProvide_wsdl =  sfConfig::get('ToneProvide_wsdl');
        $huaweiAcc =  sfConfig::get('portalAccount');
        $huaweiPwd =  sfConfig::get('portalPwd');
        $queryToneEvt = new QueryToneEvt(
            $huaweiAcc,$huaweiPwd,'1',
            null,null,null,null,
            trim($rbtCode),'2'
        );
        $crbtCaller = new CRBTCaller();
        $querySettingResp = $crbtCaller->exec($queryToneEvt, 'QueryToneEvt', 'queryTone', $toneProvide_wsdl, $toneProvide_namespace);
        $toneID = $querySettingResp->queryToneInfos[0]->toneID;
        $operateType = "1";//hide
        $queryToneEvt = new HiddenAndResumeToneEvt(
            $huaweiAcc,$huaweiPwd,'1',
            null,"3","admin",$operateType,
            "1",$toneID);
        $crbtCaller = new CRBTCaller();
        $querySettingResp = $crbtCaller->exec($queryToneEvt, 'HiddenAndResumeToneEvt', 'hiddenAndResumeTone', $toneProvide_wsdl, $toneProvide_namespace);
        sfContext::getInstance()->getLogger()->err("HideRBT: code = $rbtCode, ret = $querySettingResp->returnCode");
  }
  protected function addFiltersCriteria($c)
  {
    
    if (isset($this->filters['rbt_id_is_empty']))
    {
      $criterion = $c->getNewCriterion(RingtonePeer::RBT_ID, '');
      $criterion->addOr($c->getNewCriterion(RingtonePeer::RBT_ID, null, Criteria::ISNULL));
      $c->add($criterion);
    }
    else if (isset($this->filters['rbt_id']) && $this->filters['rbt_id'] !== '')
    {
    	$cr = new Criteria();
    	$cr->add(RingtoneExtraPeer::RBT_ID, $this->filters['rbt_id']);
    	$ringtoneExtra = RingtoneExtraPeer::doSelect($cr);
    	
    	if ($ringtoneExtra)
    	{
    		$c->add(RingtonePeer::ID, $ringtoneExtra[0]->getRingtoneId());
    		return;
		}    	
    }
    
    if (isset($this->filters['id_is_empty']))
    {
      $criterion = $c->getNewCriterion(RingtonePeer::ID, '');
      $criterion->addOr($c->getNewCriterion(RingtonePeer::ID, null, Criteria::ISNULL));
      $c->add($criterion);
    }
    else if (isset($this->filters['id']) && $this->filters['id'] !== '')
    {
      $c->add(RingtonePeer::ID, $this->filters['id']);
      return;
    }
    
    
    if (isset($this->filters['name_is_empty']))
    {
      $criterion = $c->getNewCriterion(RingtonePeer::NAME, '');
      $criterion->addOr($c->getNewCriterion(RingtonePeer::NAME, null, Criteria::ISNULL));
      $c->add($criterion);
    }
    else if (isset($this->filters['name']) && $this->filters['name'] !== '')
    {
      $c->add(RingtonePeer::NAME, '%' . strtr($this->filters['name'], '*', '%') . '%', Criteria::LIKE);
    }
    if (isset($this->filters['category_id_is_empty']))
    {
      $criterion = $c->getNewCriterion(RingtonePeer::CATEGORY_ID, '');
      $criterion->addOr($c->getNewCriterion(RingtonePeer::CATEGORY_ID, null, Criteria::ISNULL));
      $c->add($criterion);
    }
    else if (isset($this->filters['category_id']) && $this->filters['category_id'] !== '')
    {
      $c->add(RingtonePeer::CATEGORY_ID, $this->filters['category_id']);
    }
    if (isset($this->filters['created_datetime_is_empty']))
    {
      $criterion = $c->getNewCriterion(RingtonePeer::CREATED_DATETIME, '');
      $criterion->addOr($c->getNewCriterion(RingtonePeer::CREATED_DATETIME, null, Criteria::ISNULL));
      $c->add($criterion);
    }
    else if (isset($this->filters['created_datetime']))
    {
      if (isset($this->filters['created_datetime']['from']) && $this->filters['created_datetime']['from'] !== '')
      {
        $criterion = $c->getNewCriterion(RingtonePeer::CREATED_DATETIME, $this->filters['created_datetime']['from'], Criteria::GREATER_EQUAL);
      }
      if (isset($this->filters['created_datetime']['to']) && $this->filters['created_datetime']['to'] !== '')
      {
        if (isset($criterion))
        {
          $criterion->addAnd($c->getNewCriterion(RingtonePeer::CREATED_DATETIME, $this->filters['created_datetime']['to'], Criteria::LESS_EQUAL));
        }
        else
        {
          $criterion = $c->getNewCriterion(RingtonePeer::CREATED_DATETIME, $this->filters['created_datetime']['to'], Criteria::LESS_EQUAL);
        }
      }

      if (isset($criterion))
      {
        $c->add($criterion);
      }
    }
    if (isset($this->filters['composer_name_is_empty']))
    {
      $criterion = $c->getNewCriterion(RingtonePeer::COMPOSER_NAME, '');
      $criterion->addOr($c->getNewCriterion(RingtonePeer::COMPOSER_NAME, null, Criteria::ISNULL));
      $c->add($criterion);
    }
    else if (isset($this->filters['composer_name']) && $this->filters['composer_name'] !== '')
    {
      $c->add(RingtonePeer::COMPOSER_NAME, strtr('%' . $this->filters['composer_name'] . '%', '*', '%'), Criteria::LIKE);
    }
    if (isset($this->filters['creator_name_is_empty']))
    {
      $criterion = $c->getNewCriterion(RingtonePeer::CREATOR_NAME, '');
      $criterion->addOr($c->getNewCriterion(RingtonePeer::CREATOR_NAME, null, Criteria::ISNULL));
      $c->add($criterion);
    }
    else if (isset($this->filters['creator_name']) && $this->filters['creator_name'] !== '')
    {
      $c->add(RingtonePeer::CREATOR_NAME, '%' . strtr($this->filters['creator_name'] . '%', '*', '%'), Criteria::LIKE);
    }
  	if (isset($this->filters['creator_id_is_empty']))
    {
      $criterion = $c->getNewCriterion(RingtonePeer::CREATOR_ID, '');
      $criterion->addOr($c->getNewCriterion(RingtonePeer::CREATOR_ID, null, Criteria::ISNULL));
      $c->add($criterion);
    }
    else if (isset($this->filters['creator_id']) && $this->filters['creator_id'] !== '')
    {
      $c->add(RingtonePeer::CREATOR_ID, $this->filters['creator_id']);
    }
  	if (isset($this->filters['version'])) {            		    		
    	if ($this->filters['version'] == 2) {
			$c->addJoin(RingtonePeer::ID, RingtoneExtraPeer::RINGTONE_ID);
    			$c->addJoin(RingtoneExtraPeer::ORIGIN_ID, RingtoneOriginPeer::ID);
                $c->add(RingtoneOriginPeer::CHECKNUM, 'VER2_%', Criteria::LIKE);	                            
            }
        }
  }
  
  //////////////////////////////////////////////
  ////////////// GET ALL RINGTONE RELATED///////
  ////////////// THANGTV2 //////////////////////
  //////////////////////////////////////////////
  
  protected function Getringtone_Related($userid,$name,$ringid)
  {
  	if ($userid != '')
	{  	
		$rt =  new Criteria();
		$rt->add(RingtonePeer::ID, $ringid,Criteria::NOT_EQUAL);
		$rt->add(RingtonePeer::CREATOR_ID, $userid);
		$rt->add(RingtonePeer::NAME, strtr($name, '*', '%') . '%', Criteria::LIKE);
		$rt->addJoin(RingtonePeer::ID, RingtoneStatusPeer::RINGTONE_ID);
		$rt->add(RingtoneStatusPeer::RT_APPROVE, array(0,1,3),Criteria::IN);
		$this->ringtone_related = RingtonePeer::doSelect($rt);
	}
	
		$rt2 =  new Criteria();
		$rt2->add(RingtonePeer::NAME, strtr($name, '*', '%') . '%', Criteria::LIKE);
		$rt2->addJoin(RingtonePeer::ID, RingtoneStatusPeer::RINGTONE_ID);
		$rt2->add(RingtoneStatusPeer::RT_APPROVE, array(0,1,3),Criteria::IN);
		$rt2->setLimit(10);
		$rt2->addDescendingOrderByColumn(RingtonePeer::CREATED_DATETIME);
		$this->ringtone_related_all = RingtonePeer::doSelect($rt2);
	
  }
  
  // FOR AJAX
  public function executeRelation()
  {
  	$id = $this->getRequest()->getParameter('ringid');
    $ring = RingtonePeer::retrieveByPK($id);
    
  	$userId = $ring->getCreatorId();
  	$name = $this->getRequest()->getParameter('name');
	
  	$this->Getringtone_Related($userId,$name,$id);
	  	
  }
  
  //For VMS Approve Multi-Ringtone
  public function executeVmsApproveAll()
  {
  	$ringIds = $this->getRequest()->getParameter('vmsapprove');
  	if(isset($ringIds) && count($ringIds)>0)
  	{
  		foreach ($ringIds as $id) {
  			$ringtone = RingtonePeer::retrieveByPK($id);
  			$ringtone->setRtStatus(1);	//enable ringtone
  			$ringtone->setLastUpdateDatetime(date( 'Y-m-d H:i:s', time()));
  			$ringtone->save();
  			//update ringtone_status
  			$rtstatus = RingtoneStatusPeer::retrieveByPK($id);
  			$rtstatus->setRtApprove(1);
  			$rtstatus->setRtApproveAdmin($this->getUser()->getUserName());
			$rtstatus->setRtApproveDatetime(date( 'Y-m-d H:i:s', time()));
			$rtstatus->save();
  			
  		}
  	}
  	$this->redirect('ringtone/list/nhac/chuong/duyet/vmschuaduyet');  	
  }
  
	public function executeDeleteVodanh()
	{
		$con = new MysqlDAL('propel');
    	$sql = "delete rt, rtx, rts from ringtone rt inner join ringtone_extra rtx on rt.id = rtx.ringtone_id inner join ringtone_status rts on rt.id = rts.ringtone_id where rt.creator_id = 1 AND rt.created_datetime <= date_sub(now(), INTERVAL 5 HOUR)";    	
    	$con->doUpdate($sql);
    	
    	$sql = "delete from ringtone where creator_id=1 AND created_datetime <= date_sub(now(), INTERVAL 5 HOUR);";
    	$con->doUpdate($sql);
	}
	
	public function updateUsernameSannhac($rtId, $usernameSannhac)
	{
		$con = new MysqlDAL('propel');
    	
    	$sql = "UPDATE ringtone SET username_sannhac='$usernameSannhac' WHERE id=$rtId;";
    	$con->doUpdate($sql);
	}
	
	public function updateIsUpload($rtId, $isUpload)
	{
            $con = new MysqlDAL('propel');
            $sql = "UPDATE ringtone SET is_upload='$isUpload' WHERE id=$rtId;";
            $con->doUpdate($sql);
	}
        
        public function executeAddToBanner()
        {  
            $msg = '';
            $rtId = intval($this->getRequestParameter('ringtone_id'));
            if(!RingtoneBannerPeer::checkIsExistBanner($rtId))
            {
                $rtBanner = new RingtoneBanner();
                $rtBanner->setRingtoneId($rtId);
                $rtBanner->setStatus(1);
                $rtBanner->save();
                $msg = 'Đã thêm dữ liệu vào bảng Banner';
            }
            else
            {
                $msg = 'Đã có ringtone này trong bảng Banner';
            }
            echo $msg;
        }
        public function executeRemoveRtFromBanner()
        { 
            $msg = '';
            $rtId = intval($this->getRequestParameter('ringtone_id'));
            if(RingtoneBannerPeer::checkIsExistBanner($rtId))
            {
                $c = new Criteria();
                $c->add(RingtoneBannerPeer::RINGTONE_ID, $rtId, Criteria::EQUAL);
                $rs = RingtoneBannerPeer::doDelete($c);
                $msg = 'Đã loại bỏ ringtone khỏi bảng Banner';
            }
            else
            {
                $msg = 'Hiện chưa có ringtone này trong bảng Banner';
            }
            echo $msg;
        }
}
